package com.example.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/api/marketing")
@Tag(name = "营销管理", description = "优惠券、活动等营销功能管理")
public class MarketingController {

    @GetMapping("/coupons")
    @Operation(summary = "获取优惠券列表")
    public ResponseEntity<Map<String, Object>> getCouponList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String type) {
        
        List<Map<String, Object>> couponList = Arrays.asList(
            createCouponData(1L, "新用户专享", "DISCOUNT", new BigDecimal("20.00"), "满100减20", "active"),
            createCouponData(2L, "周末特惠", "PERCENTAGE", new BigDecimal("15.00"), "全场8.5折", "active"),
            createCouponData(3L, "会员专享", "DISCOUNT", new BigDecimal("50.00"), "满300减50", "active"),
            createCouponData(4L, "节日促销", "PERCENTAGE", new BigDecimal("20.00"), "全场8折", "expired"),
            createCouponData(5L, "生日礼券", "DISCOUNT", new BigDecimal("30.00"), "满200减30", "draft")
        );
        
        // 过滤数据
        if (status != null && !status.isEmpty()) {
            couponList = couponList.stream()
                .filter(coupon -> status.equals(coupon.get("status")))
                .toList();
        }
        
        Map<String, Object> response = createPagedResponse(couponList, page, size);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/coupons")
    @Operation(summary = "创建优惠券")
    public ResponseEntity<Map<String, Object>> createCoupon(@RequestBody Map<String, Object> coupon) {
        Map<String, Object> newCoupon = createCouponData(
            System.currentTimeMillis(),
            (String) coupon.get("name"),
            (String) coupon.get("type"),
            new BigDecimal(coupon.get("value").toString()),
            (String) coupon.get("description"),
            "draft"
        );
        return ResponseEntity.ok(newCoupon);
    }

    @PutMapping("/coupons/{id}")
    @Operation(summary = "更新优惠券")
    public ResponseEntity<Map<String, Object>> updateCoupon(
            @PathVariable Long id,
            @RequestBody Map<String, Object> coupon) {
        Map<String, Object> updatedCoupon = createCouponData(
            id,
            (String) coupon.get("name"),
            (String) coupon.get("type"),
            new BigDecimal(coupon.get("value").toString()),
            (String) coupon.get("description"),
            (String) coupon.get("status")
        );
        return ResponseEntity.ok(updatedCoupon);
    }

    @DeleteMapping("/coupons/{id}")
    @Operation(summary = "删除优惠券")
    public ResponseEntity<Void> deleteCoupon(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    @PutMapping("/coupons/{id}/start")
    @Operation(summary = "启动优惠券")
    public ResponseEntity<Map<String, Object>> startCoupon(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "优惠券已启动");
        return ResponseEntity.ok(result);
    }

    @PutMapping("/coupons/{id}/stop")
    @Operation(summary = "停止优惠券")
    public ResponseEntity<Map<String, Object>> stopCoupon(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "优惠券已停止");
        return ResponseEntity.ok(result);
    }

    @DeleteMapping("/coupons/batch")
    @Operation(summary = "批量删除优惠券")
    public ResponseEntity<Map<String, Object>> batchDeleteCoupons(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "批量删除成功");
        return ResponseEntity.ok(result);
    }

    @GetMapping("/activities")
    @Operation(summary = "获取活动列表")
    public ResponseEntity<Map<String, Object>> getActivityList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        List<Map<String, Object>> activityList = Arrays.asList(
            createActivityData(1L, "双十一大促", "PROMOTION", "进行中"),
            createActivityData(2L, "新用户注册送券", "REGISTRATION", "进行中"),
            createActivityData(3L, "会员日特惠", "MEMBER_DAY", "已结束"),
            createActivityData(4L, "推荐有礼", "REFERRAL", "进行中")
        );
        
        Map<String, Object> response = createPagedResponse(activityList, page, size);
        return ResponseEntity.ok(response);
    }

    @PostMapping("/activities")
    @Operation(summary = "创建活动")
    public ResponseEntity<Map<String, Object>> createActivity(@RequestBody Map<String, Object> activity) {
        Map<String, Object> newActivity = createActivityData(
            System.currentTimeMillis(),
            (String) activity.get("name"),
            (String) activity.get("type"),
            "草稿"
        );
        return ResponseEntity.ok(newActivity);
    }

    @PutMapping("/activities/{id}")
    @Operation(summary = "更新活动")
    public ResponseEntity<Map<String, Object>> updateActivity(
            @PathVariable Long id,
            @RequestBody Map<String, Object> activity) {
        Map<String, Object> updatedActivity = createActivityData(
            id,
            (String) activity.get("name"),
            (String) activity.get("type"),
            (String) activity.get("status")
        );
        return ResponseEntity.ok(updatedActivity);
    }

    @DeleteMapping("/activities/{id}")
    @Operation(summary = "删除活动")
    public ResponseEntity<Void> deleteActivity(@PathVariable Long id) {
        return ResponseEntity.ok().build();
    }

    @GetMapping("/members")
    @Operation(summary = "获取会员列表")
    public ResponseEntity<Map<String, Object>> getMemberList(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        List<Map<String, Object>> memberList = Arrays.asList(
            createMemberData(1L, "张三", "GOLD", new BigDecimal("1250.00")),
            createMemberData(2L, "李四", "SILVER", new BigDecimal("680.00")),
            createMemberData(3L, "王五", "BRONZE", new BigDecimal("320.00")),
            createMemberData(4L, "赵六", "GOLD", new BigDecimal("2100.00"))
        );
        
        Map<String, Object> response = createPagedResponse(memberList, page, size);
        return ResponseEntity.ok(response);
    }

    @GetMapping("/members/{id}")
    @Operation(summary = "获取会员详情")
    public ResponseEntity<Map<String, Object>> getMemberDetail(@PathVariable Long id) {
        Map<String, Object> member = createMemberData(id, "会员" + id, "GOLD", new BigDecimal("1250.00"));
        return ResponseEntity.ok(member);
    }

    @PutMapping("/members/{id}/level")
    @Operation(summary = "更新会员等级")
    public ResponseEntity<Map<String, Object>> updateMemberLevel(
            @PathVariable Long id,
            @RequestBody Map<String, Object> levelUpdate) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "会员等级更新成功");
        return ResponseEntity.ok(result);
    }

    @GetMapping("/members/statistics")
    @Operation(summary = "获取会员统计")
    public ResponseEntity<Map<String, Object>> getMemberStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", 1250);
        stats.put("gold", 125);
        stats.put("silver", 380);
        stats.put("bronze", 745);
        stats.put("newThisMonth", 85);
        stats.put("activeRate", 78.5);
        
        return ResponseEntity.ok(stats);
    }

    // 辅助方法
    private Map<String, Object> createCouponData(Long id, String name, String type, 
                                                BigDecimal value, String description, String status) {
        Map<String, Object> coupon = new HashMap<>();
        coupon.put("id", id);
        coupon.put("name", name);
        coupon.put("type", type);
        coupon.put("value", value);
        coupon.put("description", description);
        coupon.put("status", status);
        coupon.put("minAmount", new BigDecimal("100.00"));
        coupon.put("maxDiscount", new BigDecimal("100.00"));
        coupon.put("totalCount", 1000);
        coupon.put("usedCount", 156);
        coupon.put("startTime", LocalDateTime.now());
        coupon.put("endTime", LocalDateTime.now().plusDays(30));
        coupon.put("createTime", LocalDateTime.now());
        
        return coupon;
    }

    private Map<String, Object> createActivityData(Long id, String name, String type, String status) {
        Map<String, Object> activity = new HashMap<>();
        activity.put("id", id);
        activity.put("name", name);
        activity.put("type", type);
        activity.put("status", status);
        activity.put("startTime", LocalDateTime.now().minusDays(5));
        activity.put("endTime", LocalDateTime.now().plusDays(25));
        activity.put("participantCount", 256);
        activity.put("createTime", LocalDateTime.now().minusDays(10));
        
        return activity;
    }

    private Map<String, Object> createMemberData(Long id, String name, String level, BigDecimal balance) {
        Map<String, Object> member = new HashMap<>();
        member.put("id", id);
        member.put("name", name);
        member.put("level", level);
        member.put("balance", balance);
        member.put("points", 1250);
        member.put("totalSpent", new BigDecimal("5680.00"));
        member.put("orderCount", 45);
        member.put("joinDate", LocalDateTime.now().minusMonths(8));
        member.put("lastOrderDate", LocalDateTime.now().minusDays(3));
        
        return member;
    }

    private Map<String, Object> createPagedResponse(List<Map<String, Object>> data, int page, int size) {
        int start = page * size;
        int end = Math.min(start + size, data.size());
        List<Map<String, Object>> pagedData = start < data.size() ? data.subList(start, end) : new ArrayList<>();

        Map<String, Object> response = new HashMap<>();
        response.put("content", pagedData);
        response.put("totalElements", data.size());
        response.put("totalPages", (int) Math.ceil((double) data.size() / size));
        response.put("size", size);
        response.put("number", page);
        return response;
    }
}
